<template>
  <view class="edit-collage-page">
    <!-- 顶部快速选择 -->
    <view class="top-bar">
      <view class="select-row">
        <view class="select-item">
          <text class="select-emoji">💼</text>
          <picker :value="occasionIndex" :range="occasions" @change="onOccasionChange">
            <view class="select-pill" :class="{ selected: formData.occasion }">
              <text class="select-text">{{ formData.occasion || '场合' }}</text>
              <text class="arrow-icon">›</text>
            </view>
          </picker>
        </view>
        
        <view class="select-item">
          <text class="select-emoji">❄️</text>
          <picker :value="seasonIndex" :range="seasons" @change="onSeasonChange">
            <view class="select-pill" :class="{ selected: formData.season }">
              <text class="select-text">{{ formData.season || '季节' }}</text>
              <text class="arrow-icon">›</text>
            </view>
          </picker>
        </view>
      </view>
      
      <view class="save-btn" @click="saveCollage">
        <text class="save-emoji">✨</text>
        <text class="save-text">完成</text>
      </view>
    </view>

    <!-- LeaferJS 画布区域 -->
    <view class="canvas-wrapper">
      <canvas
        id="collageCanvas"
        type="2d"
        class="collage-canvas"
        @touchstart="receiveEvent"
        @touchmove="receiveEvent"
        @touchend="receiveEvent"
        @touchcancel="receiveEvent"
      ></canvas>
      
      <!-- 悬浮操作按钮 -->
      <view class="float-actions">
        <view class="action-btn bg-btn" @click="addBackground">
          <text class="action-emoji">🎨</text>
        </view>
        <view class="action-btn cloth-btn" @click="addClothImage">
          <text class="action-emoji">👕</text>
        </view>
        <view class="action-btn photo-btn" @click="addFreeImage">
          <text class="action-emoji">📷</text>
        </view>
      </view>
      
      <!-- 操作提示标签 -->
      <view class="hint-tags">
        <view class="hint-tag">
          <text class="hint-emoji">💡</text>
          <text class="hint-text">长按图片可拖动</text>
        </view>
      </view>
    </view>

  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onReady, onUnload, onLoad } from '@dcloudio/uni-app'
// #ifdef MP-WEIXIN
import { Leafer, Rect, Image as LeaferImage, Group, useCanvas } from '@leafer-ui/miniapp'
// #endif

const leaferRef = ref(null)
const canvasWidth = ref(0)
const canvasHeight = ref(0)
const imageElements = ref([]) // 存储所有添加的图片元素

const occasions = ['工作', '运动', '休闲', '约会', '度假']
const seasons = ['春', '夏', '秋', '冬', '所有季节']
const occasionIndex = ref(0)
const seasonIndex = ref(0)

const formData = reactive({
  occasion: '',
  season: '',
  note: '',
  images: [] // 存储图片路径
})

const collageId = ref(null)

// #ifdef MP-WEIXIN
useCanvas('canvas', uni)

onLoad((options) => {
  if (options.id) {
    collageId.value = options.id
    // TODO: 加载已有搭配数据
  }
})

onReady(() => {
  initLeafer()
})
// #endif

function initLeafer() {
  try {
    // 小程序环境需要 requestAnimationFrame polyfill
    // #ifdef MP-WEIXIN
    if (typeof wx !== 'undefined' && !wx.requestAnimationFrame) {
      wx.requestAnimationFrame = (cb) => setTimeout(cb, 16)
      wx.cancelAnimationFrame = (id) => clearTimeout(id)
      console.log('✅ requestAnimationFrame polyfill 已加载')
    }
    // #endif
    
    const systemInfo = uni.getSystemInfoSync()
    const windowWidth = systemInfo.windowWidth
    const windowHeight = systemInfo.windowHeight
    
    // 画布尺寸（减去顶部和底部工具栏）
    canvasWidth.value = windowWidth
    canvasHeight.value = windowHeight - 100 - 140 // 减去工具栏高度
    
    leaferRef.value = new Leafer({
      view: 'collageCanvas',
      width: canvasWidth.value,
      height: canvasHeight.value
    })
    
    // 添加柔和的渐变背景色
    const background = new Rect({
      x: 0,
      y: 0,
      width: canvasWidth.value,
      height: canvasHeight.value,
      fill: '#FFF5F7'  // 温柔的淡粉色
    })
    leaferRef.value.add(background)
    
    console.log('✅ LeaferJS 初始化成功')
  } catch (e) {
    console.error('❌ LeaferJS 初始化失败:', e)
  }
}

// 添加背景色
function addBackground() {
  uni.showActionSheet({
    itemList: ['💕 淡粉色', '💜 淡紫色', '🤍 纯白色', '🌸 樱花粉', '🌊 天空蓝', '🌿 薄荷绿'],
    success: (res) => {
      const colors = ['#FFF5F7', '#F3E8FF', '#FFFFFF', '#FFE5EC', '#E8F4FF', '#E8FFF0']
      const background = leaferRef.value.children[0]
      if (background) {
        background.fill = colors[res.tapIndex]
        // 触觉反馈
        uni.vibrateShort({ type: 'light' })
      }
    }
  })
}

// 添加单品图片（从衣橱）
function addClothImage() {
  const outfits = uni.getStorageSync('outfits') || []
  if (outfits.length === 0) {
    uni.showToast({ 
      title: '衣橱里还没有单品哦~', 
      icon: 'none',
      duration: 2000
    })
    return
  }
  
  uni.showActionSheet({
    itemList: outfits.map(item => `${item.brand || '未命名'} ${item.season ? '· ' + item.season : ''}`),
    success: (res) => {
      const outfit = outfits[res.tapIndex]
      if (outfit.image) {
        addImageToCanvas(outfit.image)
        // 触觉反馈
        uni.vibrateShort({ type: 'light' })
      }
    }
  })
}

// 添加自由图片
function addFreeImage() {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      addImageToCanvas(res.tempFilePaths[0])
      // 触觉反馈
      uni.vibrateShort({ type: 'medium' })
    }
  })
}

// 将图片添加到画布
function addImageToCanvas(imagePath) {
  if (!leaferRef.value) return
  
  // 获取图片信息
  uni.getImageInfo({
    src: imagePath,
    success: (info) => {
      const maxSize = 200 // 最大尺寸
      let width = info.width
      let height = info.height
      
      // 等比例缩放
      if (width > maxSize || height > maxSize) {
        const ratio = Math.min(maxSize / width, maxSize / height)
        width = width * ratio
        height = height * ratio
      }
      
      // 创建可拖动的图片组
      const group = new Group({
        x: canvasWidth.value / 2 - width / 2,
        y: canvasHeight.value / 2 - height / 2,
        draggable: true,
        around: 'center'
      })
      
      const image = new LeaferImage({
        url: imagePath,
        width,
        height
      })
      
      group.add(image)
      leaferRef.value.add(group)
      
      imageElements.value.push({
        path: imagePath,
        element: group
      })
      
      formData.images.push(imagePath)
      
      console.log('图片已添加到画布')
    },
    fail: (err) => {
      console.error('获取图片信息失败:', err)
      uni.showToast({ title: '图片加载失败', icon: 'none' })
    }
  })
}

// 触摸事件转发
function receiveEvent(e) {
  if (leaferRef.value) leaferRef.value.receiveEvent(e)
}

// 场合变化
function onOccasionChange(e) {
  occasionIndex.value = e.detail.value
  formData.occasion = occasions[e.detail.value]
  // 触觉反馈
  uni.vibrateShort({ type: 'light' })
}

// 季节变化
function onSeasonChange(e) {
  seasonIndex.value = e.detail.value
  formData.season = seasons[e.detail.value]
  // 触觉反馈
  uni.vibrateShort({ type: 'light' })
}

// 保存搭配
function saveCollage() {
  if (!formData.occasion || !formData.season) {
    uni.showToast({ 
      title: '别忘了选择场合和季节哦~', 
      icon: 'none',
      duration: 2000
    })
    return
  }
  
  if (formData.images.length === 0) {
    uni.showToast({ 
      title: '还没有添加图片呢~', 
      icon: 'none',
      duration: 2000
    })
    return
  }
  
  // 触觉反馈
  uni.vibrateShort({ type: 'medium' })
  
  // 生成封面图（使用第一张图片）
  const coverImage = formData.images[0] || ''
  
  const collage = {
    id: collageId.value || Date.now(),
    occasion: formData.occasion,
    season: formData.season,
    note: formData.note,
    images: formData.images,
    coverImage,
    createTime: Date.now()
  }
  
  const collages = uni.getStorageSync('collages') || []
  
  if (collageId.value) {
    // 编辑模式：更新已有搭配
    const index = collages.findIndex(item => item.id === collageId.value)
    if (index > -1) {
      collages[index] = collage
    }
  } else {
    // 新增模式：添加到列表开头
    collages.unshift(collage)
  }
  
  uni.setStorageSync('collages', collages)
  
  uni.showToast({ 
    title: '✨ 保存成功', 
    icon: 'success',
    duration: 1500
  })
  
  setTimeout(() => {
    uni.switchTab({
      url: '/pages/collage/index'
    })
  }, 1500)
}

onUnload(() => {
  console.log('🔄 开始清理 LeaferJS 资源...')
  
  // 清理 LeaferJS 实例
  if (leaferRef.value) {
    try {
      // 停止所有渲染
      leaferRef.value.stop()
      // 销毁实例
      leaferRef.value.destroy()
      leaferRef.value = null
      console.log('✅ LeaferJS 实例已销毁')
    } catch (e) {
      console.error('❌ 清理 LeaferJS 失败:', e)
    }
  }
  
  // 清理图片元素引用
  imageElements.value = []
  
  console.log('✅ 页面资源清理完成')
})
</script>

<style lang="scss" scoped>
.edit-collage-page {
  width: 100%;
  height: 100vh;
  background: linear-gradient(135deg, #FFF5F7 0%, #F3E8FF 100%);
  display: flex;
  flex-direction: column;
  position: relative;
}

.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 32rpx;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20rpx);
  box-shadow: 0 4rpx 20rpx rgba(255, 182, 193, 0.1);
  position: relative;
  z-index: 100;
}

.select-row {
  display: flex;
  gap: 16rpx;
  align-items: center;
}

.select-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.select-emoji {
  font-size: 32rpx;
  line-height: 1;
}

.select-pill {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 20rpx;
  background: #F8F9FF;
  border-radius: 24rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  
  &.selected {
    background: linear-gradient(135deg, #FFE5EC 0%, #F3E8FF 100%);
    border-color: rgba(216, 112, 147, 0.3);
    box-shadow: 0 4rpx 12rpx rgba(255, 182, 193, 0.2);
  }
}

.select-text {
  font-size: 26rpx;
  color: #8B7B8B;
  font-weight: 500;
  line-height: 1;
  
  .selected & {
    color: #D87093;
    font-weight: 600;
  }
}

.arrow-icon {
  font-size: 28rpx;
  color: #B8A8B8;
  line-height: 1;
  
  .selected & {
    color: #D87093;
  }
}

.save-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 28rpx;
  background: linear-gradient(135deg, #FFB6C1 0%, #DDA0DD 100%);
  color: #fff;
  border-radius: 28rpx;
  box-shadow: 0 6rpx 20rpx rgba(255, 182, 193, 0.4);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  
  &:active {
    transform: scale(0.95);
    box-shadow: 0 3rpx 12rpx rgba(255, 182, 193, 0.3);
  }
}

.save-emoji {
  font-size: 28rpx;
  line-height: 1;
}

.save-text {
  font-size: 28rpx;
  font-weight: 600;
  line-height: 1;
}

.canvas-wrapper {
  flex: 1;
  position: relative;
  overflow: hidden;
  background: linear-gradient(135deg, #FFF5F7 0%, #F3E8FF 100%);
  border-radius: 32rpx 32rpx 0 0;
  margin-top: 8rpx;
}

.collage-canvas {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
}

/* 悬浮按钮组 */
.float-actions {
  position: absolute;
  right: 32rpx;
  bottom: 40rpx;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  z-index: 999;
  pointer-events: auto;
}

.action-btn {
  width: 96rpx;
  height: 96rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 32rpx rgba(255, 182, 193, 0.5);
  transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  border: 3rpx solid rgba(255, 255, 255, 0.8);
  
  &::before {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background: inherit;
    opacity: 0.3;
    transform: scale(0.9);
    transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
  }
  
  &:active {
    transform: scale(0.9);
    box-shadow: 0 4rpx 16rpx rgba(255, 182, 193, 0.6);
    
    &::before {
      transform: scale(1.2);
      opacity: 0;
    }
  }
}

.bg-btn {
  background: linear-gradient(135deg, #FFB6C1 0%, #FFD4E5 100%);
}

.cloth-btn {
  background: linear-gradient(135deg, #DDA0DD 0%, #E6A8D7 100%);
}

.photo-btn {
  background: linear-gradient(135deg, #9370DB 0%, #B19CD9 100%);
}

.action-emoji {
  font-size: 44rpx;
  line-height: 1;
  position: relative;
  z-index: 1;
}

/* 操作提示 */
.hint-tags {
  position: absolute;
  left: 32rpx;
  bottom: 60rpx;
  z-index: 999;
  pointer-events: none;
}

.hint-tag {
  display: inline-flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 20rpx;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10rpx);
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(255, 182, 193, 0.15);
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-8rpx);
  }
}

.hint-emoji {
  font-size: 24rpx;
  line-height: 1;
}

.hint-text {
  font-size: 22rpx;
  color: #8B7B8B;
  font-weight: 500;
  line-height: 1;
}

</style>



